<template>
  <div class="heatmap-chart-wrapper">
    <div ref="heatmapChart" class="chart-container"></div>
    <div v-if="loading" class="chart-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-if="!loading && isEmpty" class="chart-empty">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { Loading } from '@element-plus/icons-vue'

const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 数据 [x, y, value]
  data: {
    type: Array,
    default: () => []
  },
  // X轴类别
  xAxisData: {
    type: Array,
    default: () => []
  },
  // Y轴类别
  yAxisData: {
    type: Array,
    default: () => []
  },
  // 图表高度
  height: {
    type: String,
    default: '350px'
  },
  // 是否显示视觉映射
  showVisualMap: {
    type: Boolean,
    default: true
  },
  // 自定义颜色范围
  colors: {
    type: Array,
    default: () => ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
  },
  // 动画效果
  animation: {
    type: Boolean,
    default: true
  }
})

const heatmapChart = ref(null)
let chartInstance = null
const loading = ref(false)
const isEmpty = ref(false)

// 初始化图表配置
const getOption = () => {
  // 获取最大最小值
  const values = props.data.map(item => item[2])
  const minValue = Math.min(...values, 0)
  const maxValue = Math.max(...values, 1)

  return {
    title: props.title ? {
      text: props.title,
      left: 'center',
      top: '10',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    } : null,
    tooltip: {
      position: 'top',
      formatter: (params) => {
        return `${props.yAxisData[params.value[1]]} - ${props.xAxisData[params.value[0]]}<br/>值: ${params.value[2]}`
      },
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      height: '60%',
      top: props.title ? '100' : '80',
      left: '100',
      right: props.showVisualMap ? '100' : '20'
    },
    xAxis: {
      type: 'category',
      data: props.xAxisData,
      splitArea: {
        show: true
      },
      axisLabel: {
        fontSize: 11,
        color: '#666'
      }
    },
    yAxis: {
      type: 'category',
      data: props.yAxisData,
      splitArea: {
        show: true
      },
      axisLabel: {
        fontSize: 11,
        color: '#666'
      }
    },
    visualMap: props.showVisualMap ? {
      min: minValue,
      max: maxValue,
      calculable: true,
      orient: 'vertical',
      right: '10',
      top: 'center',
      inRange: {
        color: props.colors
      },
      textStyle: {
        color: '#666'
      }
    } : null,
    series: [
      {
        type: 'heatmap',
        data: props.data,
        label: {
          show: true,
          fontSize: 11,
          color: '#fff'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    animation: props.animation
  }
}

// 初始化图表
const initChart = () => {
  if (!heatmapChart.value) return

  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(heatmapChart.value)
  chartInstance.setOption(getOption())

  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小改变
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 加载数据
const loadData = () => {
  if (!props.data || props.data.length === 0) {
    isEmpty.value = true
    return
  }

  isEmpty.value = false
  nextTick(() => {
    initChart()
  })
}

// 监听数据变化
watch(() => props.data, () => {
  loadData()
}, { deep: true })

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露刷新方法
defineExpose({
  refresh: loadData,
  getInstance: () => chartInstance
})
</script>

<style scoped lang="scss">
.heatmap-chart-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);

  .chart-container {
    width: 100%;
    height: 100%;
  }

  .chart-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #999;
    font-size: 14px;

    .el-icon {
      font-size: 32px;
    }
  }

  .chart-empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
  }
}
</style>

